package com.example.test.util;


import org.apache.commons.io.FileUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;

/**
* @Author: 林文峰 
* @Date 2020/6/19 0019 11:13
*/
public class MultipartFileToFile {

	/**
	 * MultipartFile 转 File
	 * 会在项目目录产生一个临时文件，需要删除
	 * @param file
	 * @throws Exception
	 */
	public static File multipartFileToFile(MultipartFile file) {
		File toFile = null;
		if (file.equals("") || file.getSize() <= 0) {
			file = null;
		} else {
			InputStream ins = null;
			try {
				//获取一个输入流
				ins = file.getInputStream();
				toFile = new File(file.getOriginalFilename());
				inputStreamToFile(ins, toFile);
			} catch (IOException e) {
				e.printStackTrace();
			}finally {
				if (ins != null){
					try {
						ins.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}
		return toFile;
	}

	//获取流文件
	private static void inputStreamToFile(InputStream ins, File file) {
		try {
			OutputStream os = new FileOutputStream(file);
			int bytesRead = 0;
			byte[] buffer = new byte[8192];
			while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
				os.write(buffer, 0, bytesRead);
			}
			os.close();
			ins.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 删除本地临时文件
	 * @param file
	 */
	public static void deleteTempFile(File file) {
		if (file != null) {
			File del = new File(file.toURI());
			del.delete();
		}
	}
}